<script setup>
import FillBlank from '@/views/components/FillBlank.vue'
import SingleBlank from '@/views/components/SingleBlank.vue'
import MusicPlayer from './components/MusicPlayer.vue'
import RadioOption from '@/views/components/RadioOption.vue'
import CheckBoxOption from '@/views/components/CheckBoxOption.vue'
import TheTimer from '@/components/TheTimer.vue'
import RecordItem from '@/views/components/RecordItem.vue'
import { computed, nextTick, onBeforeMount, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { apiGetExamApi, apiSubmitTopic, apiSubmitExam, apiSubmitDuration } from '@/api/exam'
import { useRoute, useRouter } from 'vue-router'
import { showImagePreview, showToast } from 'vant'
import { setDocumentTitle } from '@/utils/util.js'

const router = useRouter()
const route = useRoute()

const musicComponent = ref()
const timer = ref(null)
const showPopup = ref(false)

const specialType = ['数字题'] // 专项练习中不同题型处理

const state = reactive({
    examId: 0,
    groupList: [],
    subjectType: 0,
    seriesType: '',
    listenAudio: '',
    articleTitle: '',
    tabList: ['题目', '提交记录'],
    currentTab: '',
    practiceType: '',
    examName: '',
    recordId: null,
    scrollYList: { tab1: 0, tab2: 0, tab3: 0 },
    device: '',
    showSubmit: true,
    questionType: ''
})

const keyboardHeight = ref()

const orgPassage = ref([]) // 文章和译文列表

const showTranslate = ref(false) // 显示翻译

const showInput = ref(true) // 解决ios收起键盘后点击页面仍会触发一次focus事件

const audioCurrentTime = computed(() => route.query.currentTime)

onBeforeMount(() => {
    document.querySelector('body').setAttribute('style', 'background:#fff;')
    const query = route.query
    state.device = query.device
    setDocumentTitle(query.title ? query.title : '')
    getExamData(query.id)
})
onMounted(() => {
    // 1 判断是阅读 听力 还是其他
    state.currentTab = '题目'
    document.addEventListener('visibilitychange', handleVisibilityChange)
    window.addEventListener('resize', handleReSize, true)
})

onBeforeUnmount(() => {
    unAllHandle()
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('resize', handleReSize)
})

// 监听软键盘弹起和收起，处理音频组件的展示
function handleReSize() {
    const height = window.innerHeight
    state.showSubmit = height > keyboardHeight.value
    keyboardHeight.value = height
}

// 开始计时
const startTime = () => {
    timer.value.startTime()
}

// 退出计时
const stopTime = () => {
    timer.value.stopTime()
}

// 获取题目列表
function getExamData(id) {
    id = id || 11
    const toast = showToast({
        type: 'loading',
        message: '加载中...',
        forbidClick: true,
        duration: 0
    })
    apiGetExamApi({
        recordId: id
    }).then((res) => {
        toast.close()
        state.examId = res.examId
        state.practiceType = res.practiceType
        state.subjectType = res.subjectType
        state.seriesType = res.seriesType
        state.listenAudio = res.listenAudio
        state.examName = res.examName
        state.groupList = res.partList[0].groupList
        orgPassage.value = res.partList[0]?.translates
        state.articleTitle = res.partList[0].title
        state.recordId = res.recordId
        state.questionType = res.questionType
        if (state.subjectType === 1) {
            const questionType = res.questionType == '数字题' ? '数字题' : '听力'
            setDocumentTitle(res.seriesType + ' ' + questionType)
            state.tabList = ['题目', '提交记录']
            state.currentTab = route.query.tab ? route.query.tab : '题目'
        } else if (state.subjectType === 2) {
            setDocumentTitle(res.seriesType + ' ' + '阅读')
            state.tabList = ['文章', '题目', '提交记录']
            state.currentTab = route.query.tab ? route.query.tab : '文章'
        }
        timer.value.initTime(res.duration)
        initAllHandle()
    })
}

// 查看大图
const showBIgImage = (url) => {
    showImagePreview([url])
}

// 输入框获取焦点
const inputFocus = () => {
    const isPad = /iPad/.test(navigator.userAgent)
    const isMobile =
        /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) &&
        !isPad
    const isPC = !isPad && !isMobile
    if (!isPC) {
        // 手机上处理底部固定内容
        state.showSubmit = false
    }
}

// 保存题目
const saveTopic = (data) => {
    console.log('失去焦点', data)
    // const isIos = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    // if (isIos) {
    //     showInput.value = false
    //     setTimeout(() => {
    //         showInput.value = true
    //     }, 0)
    // }
    // 手机上处理底部固定内容
    setTimeout(() => {
        // 防止ios 中文键盘 输入内容点完成后 input重新获取焦点的问题
        state.showSubmit = true
    }, 200)
    const params = {
        recordId: state.recordId,
        topicId: data.topicId,
        duration: timer.value.getTime(),
        userAnswer: data.userAnswer
    }
    apiSubmitTopic(params).then(() => {})
}

// 弹窗
function openPopup() {
    showPopup.value = true
}
function handleCancel() {
    showPopup.value = false
}

function handleOk() {
    showPopup.value = false
    submitExam()
}

// 提交试卷
function submitExam() {
    stopTime()
    apiSubmitExam({
        recordId: state.recordId,
        duration: timer.value.getTime()
    }).then(() => {
        showToast({
            message: '提交成功',
            forbidClick: true
        })
        setTimeout(() => {
            window.scrollTo(0, 0)
            router.replace({
                name: 'record',
                query: {
                    id: state.recordId
                }
            })
        }, 1000)
    })
}

// 提交作答时间
function submitDuration(time) {
    apiSubmitDuration({
        recordId: state.recordId,
        duration: time
    }).then(() => {})
}

// 切换tab标签
const changeTab = (item) => {
    // 记录tab滚动的高度
    if (state.currentTab === '题目') {
        state.scrollYList.tab1 = window.scrollY
    } else if (state.currentTab === '提交记录') {
        state.scrollYList.tab3 = window.scrollY
    } else if (state.currentTab === '文章') {
        state.scrollYList.tab2 = window.scrollY
    }

    state.currentTab = item
    if (item === '题目' || item === '文章') {
        document.querySelector('body').setAttribute('style', 'background:#ffffff;')
        initAllHandle()
    } else {
        document.querySelector('body').setAttribute('style', 'background:#f6f8fc;')
        unAllHandle()
        const query = route.query
        const currentTime = musicComponent.value && musicComponent.value.getCurrentTime() || undefined
        console.log(currentTime, 1)
        router.replace({
            name: 'recordList',
            query: {
                id: query.id,
                examId: state.examId,
                subjectType: state.subjectType,
                seriesType: state.seriesType,
                currentTime
            }
        })
    }

    setTimeout(() => {
        // 改变tab对应的高度
        if (state.currentTab === '题目') {
            window.scrollTo(0, state.scrollYList.tab1)
        } else if (state.currentTab === '提交记录') {
            window.scrollTo(0, state.scrollYList.tab3)
        } else if (state.currentTab === '文章') {
            window.scrollTo(0, state.scrollYList.tab2)
        }
    }, 0)
}

// 进入页面初始化时间和音频播放
const initAllHandle = () => {
    try {
        // 1. 初始化时间
        startTime()

        if (state.subjectType === 1) {
            nextTick(() => {
                // 2. 音频播放
                if (musicComponent.value) {
                    musicComponent.value.play()
                }
            })
        }
    } catch (e) {
        console.error(e)
    }
}

// 判断手机是否锁屏
const handleVisibilityChange = () => {
    if (document.visibilityState === 'hidden') {
        unAllHandle()
    } else {
        initAllHandle()
    }
}

// 也换tab和页面退出的时候销毁或停止所有的计时和音频播放
const unAllHandle = () => {
    try {
        const durtion = timer.value.getTime()
        submitDuration(durtion)
        // 1.暂停时间
        stopTime()
        if (state.subjectType === 1) {
            // 2.停止音频播放
            musicComponent.value.pause()
        }
    } catch (e) {
        console.error(e)
    }
}
</script>
<template>
    <div>
        <div class="header">
            <div class="class-list">
                <div
                    class="class-item"
                    :class="{ active: item === state.currentTab }"
                    v-for="(item, index) in state.tabList"
                    :key="index"
                    @click="changeTab(item)">
                    {{ item }}
                </div>
            </div>
            <div
                v-show="state.currentTab === '题目' || state.currentTab === '文章'"
                class="time-blank" :class="{empty:specialType.includes(state.questionType)}">
                <!-- <div class="timer-title" v-if="!specialType.includes(state.questionType)">{{ state.practiceType }} &nbsp; {{ state.examName }}</div> -->
                <div class="timer-title" v-if="!specialType.includes(state.questionType)">{{ state.examName }}</div>
                <div>
                    <the-timer ref="timer"></the-timer>
                </div>
            </div>
        </div>

        <div class="topic-content" v-show="state.currentTab === '题目'">
            <div class="content" v-for="(item, index) in state.groupList" :key="index">
                <div class="content-text" v-html="item.groupName" />
                <div class="content-text" v-html="item.groupDesc" />
                <div class="content-text" style="text-align: center;font-size: 17px;font-weight: bold;" v-html="item.title" />
                <div class="imgUrl" v-if="item.imgUrl" @click="showBIgImage(item.imgUrl)">
                    <img :src="item.imgUrl" alt="" />
                </div>
                <template v-if="item.itemList">
                    <div
                        class="flex-item-start"
                        v-for="(sub, subIndex) in item.itemList"
                        :key="'sub' + subIndex">
                        <b class="num-text">{{ sub.optionCode }}</b>
                        <label>{{ sub.optionName }}</label>
                    </div>
                    <br />
                </template>
                <template v-if="item.itemTitle">
                    <div class="item-title" v-html="item.itemTitle" />
                </template>
                <FillBlank
                    v-if="(item.type === 1 || item.type === 16) && showInput"
                    :topicList="item.topicList"
                    @input-blue="saveTopic"
                    @input-focus="inputFocus"></FillBlank>
                <SingleBlank
                    v-if="[7, 4, 3, 14, 12, 10, 11, 5, 9].includes(item.type) && showInput"
                    :keyClass="'key' + item.orderNum"
                    :topicList="item.topicList"
                    @input-blue="saveTopic"
                    @input-focus="inputFocus"></SingleBlank>
                <radio-option
                    v-if="item.type === 2 || item.type === 15 || item.type === 8"
                    :topic-list="item.topicList"
                    @changeHandle="saveTopic"></radio-option>
                <check-box-option
                    v-if="item.type === 6"
                    :topic-list="item.topicList"
                    @changeHandle="saveTopic"></check-box-option>
                <div v-if="index + 1 < state.groupList.length" class="bottom-line"></div>
            </div>
            <div
                id="submit"
                class="fixed-bottom"
                v-show="state.subjectType === 1 && state.showSubmit">
                <MusicPlayer v-if="state.listenAudio" ref="musicComponent" :url="state.listenAudio" :memory-time="audioCurrentTime"></MusicPlayer>
                <div
                    v-if="state.recordId && state.subjectType === 1"
                    class="submit-btn"
                    @click="openPopup">
                    提交
                </div>
            </div>

            <div
                id="submit"
                v-if="state.recordId && state.subjectType === 2 && state.showSubmit"
                class="submit-blank">
                <div class="submit-button" @click="openPopup">提交</div>
            </div>
        </div>
        <div v-if="state.currentTab === '提交记录'" class="record-content">
            <!-- 此记录单独拆出去 -->
            <!--<RecordItem :exam-id="state.examId"></RecordItem>-->
        </div>
        <div v-show="state.currentTab === '文章'" class="question-content">
            <div class="article-title" v-html="state.articleTitle"></div>
            <div class="html-content" >
                <template v-for="(item, index) in orgPassage" :key="index">
                    <div v-html="item.orgContent"></div>
                    <br>
                    <div v-show="showTranslate">
                        <div class="translate">{{item.content}}</div>
                        <br>
                    </div>
                </template>
            </div>
            <div class="end-flag">- End -</div>
            <div :class="['translate-btn', {'show-translate': showTranslate}]" @click="showTranslate = !showTranslate">
                <img src="@/assets/ic_fanyi@2x.png" alt="">
            </div>
        </div>

        <!--弹窗-->
        <van-popup v-model:show="showPopup" round :style="{ padding: '20px', width: '300px' }">
            <div class="popup-blank">
                <div class="title">温馨提示</div>
                <div class="popup-content">
                    提交后无法修改，<br />
                    确定提交吗？
                </div>
                <div class="btn-list">
                    <div class="btn popup-cancel" @click="handleCancel">取消</div>
                    <div class="btn popup-ok" @click="handleOk">确定</div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<style>
p > .section-tip {
    font-weight: bold !important;
}
p > i {
    font-style: italic;
}
</style>
<style scoped lang="scss">
.header {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1;
    background-color: #ffffff;
    width: 100%;
}
.class-list {
    height: 46px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    .class-item {
        padding: 0 15px;
        color: #999999;
        position: relative;
        text-align: center;
    }
    .active {
        color: #666666;
        font-weight: bold;
        font-size: 1rem;
    }
    .active::before {
        position: absolute;
        left: calc(50% - 9px);
        text-align: center;
        bottom: -4px;
        content: ' ';
        width: 18px;
        height: 3px;
        background: #fd453d;
        border-radius: 2px;
    }
}
.time-blank {
    background: #f6f6f6;
    height: 37px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #333333;
    font-size: 14px;
    padding: 0 16px;
    .timer-title {
        color: #333333;
        font-size: 0.933rem;
    }
}
.empty::before{
    content: '';
    display: inline-block;
    flex: auto;
}
.record-content {
    padding: 46px 0 10px 0;
    line-height: 30px;
    .article-title {
        text-align: center;
    }
}

.question-content {
    padding: 5.533rem 1rem 6rem 1rem;
    line-height: 30px;
    word-break: break-word;
    .article-title {
        text-align: center;
    }
    :deep(.html-content) {
        ::v-deep img {
            width: 100% !important;
        }
        .translate{
            color: #999;
        }
    }
    .end-flag {
        font-size: 15px;
        color: #999999;
        text-align: center;
        line-height: 30px;
        height: 30px;
    }
    .translate-btn{
        width: 2.67rem;
        height: 2.67rem;
        border-radius: .67rem;
        background-color: rgba(102, 102, 102, .8);
        position: fixed;
        right: 1rem;
        bottom: 11.67rem;
        img{
            width: 1.13rem;
            height: 1.13rem;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    }
    .show-translate{
        background-color: rgba(117, 164, 255, .8);
    }
}

.topic-content {
    padding: 5.533rem 1rem 6rem 1rem;
}
.item-title{
    font-size: 17px;
    font-weight: bold;
    text-align: center;
}
.content {
    padding-top: 10px;
    .content-text {
        padding-bottom: 10px;
    }
    .imgUrl {
        width: 100%;
        img {
            width: 100%;
            height: auto;
        }
    }
    .bottom-line {
        background-color: #f5f5f5;
        height: 5px;
    }
}
.fixed-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    padding-bottom: 1.333rem;
    background: hsla(0, 0%, 100%, 1);
}
.submit-btn {
    position: absolute;
    right: 30px;
    bottom: 2.2rem;
    font-size: 0.933rem;
    color: #fd453d;
    font-weight: bold;
}
/* 阅读提交按钮 */
.submit-blank {
    border-top: 1px solid #ececec;
    padding: 10px 15px 30px 15px;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #ffffff;
    .submit-button {
        height: 2.467rem;
        line-height: 2.467rem;
        text-align: center;
        background: #fd453d;
        border-radius: 1.23rem;
        color: #ffffff;
        font-size: 0.933rem;
    }
}
b {
    font-weight: bold !important;
}
.flex-item-start {
    display: flex;
    justify-content: flex-start;
    line-height: 2rem;
}
.num-text {
    font-weight: bold;
    font-size: 0.87rem;
    color: black;
    padding-right: 4px;
}

/* 弹窗 */
.popup-blank {
    .title {
        color: #999999;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
    }
    .popup-content {
        color: #333333;
        font-size: 14px;
        text-align: center;
    }
    .btn-list {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        margin-top: 20px;
        .btn {
            width: 110px;
            height: 40px;
            background: #f6f8fc;
            border-radius: 20px;
            font-size: 14px;
            text-align: center;
            line-height: 40px;
        }
        .popup-cancel {
            background: #f6f8fc;
            color: #333333;
        }
        .popup-ok {
            background: #fd453d;
            color: #ffffff;
        }
    }
}
</style>
